package net.neptech.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.neptech.dto.sys.StaffDTO;
import net.neptech.exception.BusinessException;
import net.neptech.mapper.DeptMapper;
import net.neptech.mapper.StaffMapper;
import net.neptech.model.sys.Dept;
import net.neptech.page.PageQuery;
import net.neptech.page.TableDataInfo;
import net.neptech.repository.DeptRepo;
import net.neptech.service.DeptService;
import net.neptech.utils.SecurityUtils;
import net.neptech.vm.ResponseResult;
import net.neptech.vo.TreeSelectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: liyuxiang
 * @Date: 2025/8/15 11:11
 * @Description: TODO
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    DeptMapper deptMapper;
    @Autowired
    StaffMapper staffMapper;
    @Autowired
    private DeptRepo deptRepo;

    @Override
    public List<Dept> selectDeptList(Dept dept) {

        return deptMapper.selectDeptList(dept);
    }

    @Override
    public Dept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    @Override
    public void updateDept(Dept dept) {
        deptMapper.updateDept(dept);
    }

    @Override
    public void insertDept(Dept dept) {
        Dept info = deptMapper.selectDeptById(dept.getParentId());
        if (info != null) {
            dept.setAncestors(info.getAncestors() + dept.getParentId());
        }
        deptMapper.insert(dept);
    }

    @Override
    public void deleteDeptById(Long deptId) {
        //判断是否有子节点
        if (hasChildByDeptId(deptId)) {
            throw new BusinessException(400, "存在下级部门,不允许删除");
        }
        //判断是否有员工
        List<StaffDTO> staffsByDeptId = staffMapper.getStaffsByDeptId(deptId);
        if (staffsByDeptId != null && !staffsByDeptId.isEmpty()) {
            throw new BusinessException(400, "存在医生,不允许删除");
        }
        deptMapper.deleteById(deptId);
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    @Override
    public List<TreeSelectVo> selectDeptTree(Dept dept) {
        // 1. 获取部门列表（根据传入的dept查询条件筛选）
        List<Dept> depts = selectDeptList(dept);

        // 2. 将平面列表构建成树形结构
        List<Dept> deptTree = buildDeptTree(depts);

        // 3. 将部门树转换为前端需要的树形选择VO对象
        return deptTree.stream()
                       .map(TreeSelectVo::new)  // 使用TreeSelectVo的构造方法转换每个部门节点
                       .collect(Collectors.toList());  // 收集为List
    }

    @Override
    public TableDataInfo<Dept> getDeptPage(Dept dept, PageQuery pageQuery) {
        Page<Dept> page = deptMapper.getDeptPage(dept, pageQuery.build());

        // 如果不是管理员，过滤掉顶级部门
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            List<Dept> filteredRecords = page.getRecords().stream()
                                             .filter(d -> d.getParentId() != null && d.getParentId() != 0L)
                                             .collect(Collectors.toList());
            page.setRecords(filteredRecords);
            page.setTotal(filteredRecords.size());
        }

        return TableDataInfo.build(page);
    }

    @Override
    public List<Dept> getDeptDetailByDeptName(String deptName) {
        if (deptName == null || deptName.isEmpty()) {
            throw new BusinessException(400, "科室名称不能为空");
        }

        // 调用Mapper方法查询科室详情
        List<Dept> depts = deptMapper.selectList(new LambdaQueryWrapper<>(Dept.class).eq(Dept::getDeptName, deptName));
        if (depts == null || depts.isEmpty()) {
            throw new BusinessException(404, "未找到相关科室信息");
        }
        return depts;
    }

    /**
     * 构建部门树形结构
     *
     * @param depts 部门列表
     * @return 树形结构的部门列表
     */
    private List<Dept> buildDeptTree(List<Dept> depts) {
        List<Dept> tree = new ArrayList<>();

        // 1. 首先找出所有根部门(parentId为null或0的部门)
        for (Dept dept : depts) {
            if (dept.getParentId() == null || dept.getParentId() == 0L) {
                tree.add(dept);
            }
        }

        // 2. 为每个根部门递归查找子部门
        for (Dept parent : tree) {
            findChildren(parent, depts);
        }

        return tree;
    }

    /**
     * 递归查找子部门
     *
     * @param parent 父部门
     * @param depts  所有部门列表
     */
    private void findChildren(Dept parent, List<Dept> depts) {
        // 找出当前部门的所有直接子部门
        List<Dept> children = depts.stream()
                                   .filter(dept -> parent.getDeptId().equals(dept.getParentId()))
                                   .collect(Collectors.toList());

        if (!children.isEmpty()) {
            // 将子部门添加到父部门的children集合中
            parent.getChildren().addAll(children);

            // 继续递归查找每个子部门的子部门
            for (Dept child : children) {
                findChildren(child, depts);
            }
        }
    }

    /**
     * 查询1级科室
     *
     * @return
     */
    @Override
    public List<Dept> selectOneLevelDept() {

        return deptMapper.selectList
                                 (new QueryWrapper<Dept>().eq("parent_id", 0));
    }

    /**
     * 查询旗下的科室
     */
    @Override
    public List<Dept> selectDeptByParentId(Long parentId) {
        return deptMapper.selectList
                                 (new QueryWrapper<Dept>().eq("parent_id", parentId));
    }

    @Override
    public List<Dept> getDeptDetailByDeptIds(List<Long> ids) {
        List<Dept> deptList = deptMapper.selectList(new QueryWrapper<Dept>().in("dept_id", ids));
        return deptList;
    }

    @Override
    public List<Dept> getAll() {
        return deptRepo.findAll().stream().toList();
    }
}
